package com.api.controller;

import com.api.config.SseEmitterServer;
import com.api.entity.Mailbox;
import com.api.entity.Notices;
import com.api.entity.User;
import com.api.log.Log;
import com.api.mapper.MailboxMapper;
import com.api.mapper.NoticesMapper;
import com.api.utils.ParamsUtils;
import com.api.utils.Result;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.api.entity.table.MailboxTableDef.MAILBOX;
import static com.api.entity.table.NoticesTableDef.NOTICES;
import static com.api.entity.table.UserTableDef.USER;

/**
 * @Author: yangsf
 * @CreateDate: 2024/10/24
 */

@Slf4j
@RestController
@RequestMapping("/notices")
public class NoticesController extends BaseController {


    @Autowired
    NoticesMapper noticesMapper;

    @Autowired
    MailboxMapper mailboxMapper;

    @Autowired
    SseEmitterServer sseServer;

    @Log("获取行政公告列表")
    @RequestMapping("/getList")
    public Result getList(@RequestBody Map<String,Object> params){
        QueryWrapper qw = new QueryWrapper();
        qw.select(NOTICES.ID,NOTICES.TITLE,NOTICES.STATUS,NOTICES.CREATE_TIME,USER.as("cu").USER_NAME.as("createName"),NOTICES.SEND_TIME,USER.as("su").USER_NAME.as("sendName"))
                .leftJoin(USER.as("cu")).on(USER.as("cu").ID.eq(NOTICES.CREATE_ID))
                .leftJoin(USER.as("su")).on(USER.as("su").ID.eq(NOTICES.SEND_ID))
                .where(NOTICES.STATUS.gt(0));
        if(params.containsKey("nameKeyword") && null != params.get("nameKeyword") && !StringUtils.isEmpty(params.get("nameKeyword"))){
            String nameKeyword = params.get("nameKeyword").toString();
            qw.and(NOTICES.TITLE.like(nameKeyword));
        }
        if(params.containsKey("status") && null != params.get("status") && !StringUtils.isEmpty(params.get("status"))){
            Integer status = Integer.parseInt(params.get("status").toString());
            qw.and(NOTICES.STATUS.eq(status));
        }
        qw.orderBy(NOTICES.ID.desc());
        Page page = ParamsUtils.toPage(params);
        Page<Notices> pages =noticesMapper.paginate(page,qw);
        return Result.ok(pages);
    }

    // save  del send get

    @Log("保存行政公告")
    @RequestMapping("/save")
    public Result save(@RequestBody Notices notices){
        boolean isAdd = null == notices.getId()?true:false;
        Long userId = getUserId();
        boolean b = false;
        if(isAdd){
            b = notices.setStatus(1).setCreateId(userId).setUpdateId(userId).saveOrUpdate();
        }
        else{
            b = notices.setStatus(1).setUpdateId(userId).updateById();
        }
        if(b){
            return Result.ok();
        }
        return Result.err();
    }

    @Log("获取行政公告")
    @RequestMapping("/get")
    public Result get(Long id){
        if(null == id){
            return Result.err("未获取到要发布的新闻");
        }
        Notices notices = Notices.create().setId(id).oneById();
        if(null == notices){
            return Result.err("未获取到要发布的新闻");
        }
        return Result.ok(notices);
    }


    @Log("发布行政公告")
    @RequestMapping("/send")
    public Result send(Long id){
        if(null == id){
            return Result.err("未获取到要发布的公告");
        }
        Notices notices = Notices.create().setId(id).oneById();
        if(null == notices){
            return Result.err("未获取到要发布的公告");
        }
        if(null == notices.getStatus()){
            notices.setStatus(0);
        }
        if(notices.getStatus().intValue() == 0){
            return Result.err("该公告不存在或已被删除，不能发布");
        }
        else if(notices.getStatus().intValue() == 2){
            return Result.err("该公告已发布，不能再次发布");
        }
        else if (notices.getStatus().intValue() != 1){
            return Result.err("该公告状态异常，不能允许操作");
        }
        Long userId = getUserId();
        boolean b = notices.setStatus(2).setSendId(userId).setSendTime(new Date()).updateById();
        if(b){
            // todo 发给所有人
            List<User> list = User.create()
                    .where(User::getStatus).eq(1)
                    .list();
            if(list.size()>0){
                for(User u:list){
                    Mailbox mailbox = Mailbox.create().setUserId(u.getId()).setKind(1).setRellId(id).setTitle(notices.getTitle()).setStatus(1);
                    mailbox.save();
                    //todo 发送推送
                    sseServer.sendMsg(u.getId(),mailbox);
                }
            }
            return Result.ok();
        }
        return Result.err();
    }

    @Log("删除行政公告")
    @RequestMapping("/del")
    public Result del(Long id){
        if(null == id){
            return Result.err("未获取到要发布的公告");
        }
        Notices notices = Notices.create().setId(id).oneById();
        if(null == notices){
            return Result.err("未获取到要发布的公告");
        }
        if(null == notices.getStatus()){
            notices.setStatus(0);
        }
        if(notices.getStatus().intValue() == 0){
            return Result.err("该公告不存在或已被删除，不能操作");
        }
        Long userId = getUserId();
        boolean b = notices.setStatus(0).setUpdateId(userId).updateById();
        if(b){
            List<Mailbox> list = Mailbox.create().setKind(1).setRellId(id).list();
            if(list.size()>0){
                QueryWrapper qw = new QueryWrapper();
                qw.where(MAILBOX.KIND.eq(1)).and(MAILBOX.RELL_ID.eq(id));
                mailboxMapper.deleteByQuery(qw);
            }
            return Result.ok();
        }
        return Result.err();
    }


}
